package user

import (
	"gin/model"
	"gin/model/database"
	"gin/server"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

// 定义结构体存储数据
type Permission_c struct {
	Id             int
	Pid            int
	Status         int
	PermissionName string
	PermissionUrl  string
	Children       []*Permission_c `gorm:"foreignKey:Pid;references:Id"`
}

// 权限列表
func (con Permission_c) PermissionList(c *gin.Context) {
	var permissions []*Permission_c
	if err := database.DB.Table("permission").Find(&permissions).Error; err != nil {
		c.JSON(500, gin.H{
			"error": err,
		})
		return
	}

	// 创建一个映射，方便快速查找每个权限节点
	permissionMap := make(map[int]*Permission_c)
	for _, p := range permissions {
		permissionMap[p.Id] = p
	}
	//A
	var pdata []*Permission_c
	for _, p := range permissions {
		if p.Pid == 0 {
			pdata = append(pdata, p)
		} else {
			parent, ok := permissionMap[p.Pid]
			if ok {
				if parent.Children == nil {
					parent.Children = make([]*Permission_c, 0)
				}
				parent.Children = append(parent.Children, p)
			}
		}
	}
	//c.JSON(200, gin.H{
	//	"users": pdata,
	//})
	c.HTML(http.StatusOK, "user/permissionList.html", gin.H{
		"data": pdata,
	})
}

func (con Permission_c) PermissionAdd(c *gin.Context) {
	m := &model.Permission{
		PermissionName: "",
		PermissionUrl:  "",
		Pid:            0,
	}
	m.PermissionName = c.PostForm("permission_name")
	m.PermissionUrl = c.PostForm("permission_url")
	m.Pid, _ = strconv.Atoi(c.PostForm("pid"))
	if m.PermissionName == "" || m.PermissionUrl == "" {
		c.JSON(200, gin.H{
			"code": 301,
			"msg":  "permission_name,permission_url参数不能为空",
			"data": nil,
		})
	}

	err := database.DB.Table("permission").Save(&m).Error
	if err != nil {
		server.Success(c, "添加失败", nil)
		return
	}
	server.Success(c, "添加成功", nil)
}
